<template>
  <div class="marketing-strategy-management">
    <div class="header">
      <h2>营销策略管理</h2>
      <button @click="$router.push('/dashboard')" class="back-btn">返回首页</button>
    </div>
    
    <!-- 添加策略表单 -->
    <div class="add-strategy-form">
      <input v-model="newStrategy.name" placeholder="策略名称" />
      <textarea v-model="newStrategy.description" placeholder="策略描述"></textarea>
      <select v-model="newStrategy.category_id">
        <option value="">选择商品品类</option>
        <option v-for="category in categories" :key="category.id" :value="category.id">
          {{ category.name }}
        </option>
      </select>
      <input v-model="newStrategy.discount_rate" type="number" min="0" max="100" placeholder="优惠折扣(0-100)" />
      <input type="datetime-local" v-model="newStrategy.start_time" placeholder="开始时间" />
      <input type="datetime-local" v-model="newStrategy.end_time" placeholder="结束时间" />
      <input v-model="newStrategy.duration" type="number" min="1" placeholder="持续时间(小时)" />
      <select v-model="newStrategy.status">
        <option value="active">上架</option>
        <option value="inactive">下架</option>
      </select>
      <button @click="addStrategy" :disabled="!isValidStrategy">添加策略</button>
    </div>

    <!-- 策略列表 -->
    <table class="strategy-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>策略名称</th>
          <th>描述</th>
          <th>商品品类</th>
          <th>优惠折扣</th>
          <th>开始时间</th>
          <th>结束时间</th>
          <th>持续时间</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="strategy in strategies" :key="strategy.id">
          <td>{{ strategy.id }}</td>
          <td>{{ strategy.name }}</td>
          <td>{{ strategy.description }}</td>
          <td>{{ getCategoryName(strategy.category_id) }}</td>
          <td>{{ strategy.discount_rate }}%</td>
          <td>{{ formatDateTime(strategy.start_time) }}</td>
          <td>{{ formatDateTime(strategy.end_time) }}</td>
          <td>{{ strategy.duration }}小时</td>
          <td>
            <span :class="['status-badge', strategy.status === 'active' ? 'active' : 'inactive']">
              {{ strategy.status === 'active' ? '上架' : '下架' }}
            </span>
          </td>
          <td>
            <button @click="editStrategy(strategy)">编辑</button>
            <button 
              @click="toggleStrategyStatus(strategy)"
              :class="['status-btn', strategy.status === 'active' ? 'deactivate' : 'activate']"
            >
              {{ strategy.status === 'active' ? '下架' : '上架' }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 编辑策略对话框 -->
    <div v-if="showEditDialog" class="edit-dialog">
      <div class="edit-dialog-content">
        <h3>编辑策略</h3>
        <div class="form-group">
          <label>策略名称：</label>
          <input v-model="editingStrategy.name" />
        </div>
        <div class="form-group">
          <label>策略描述：</label>
          <textarea v-model="editingStrategy.description"></textarea>
        </div>
        <div class="form-group">
          <label>商品品类：</label>
          <select v-model="editingStrategy.category_id">
            <option value="">选择商品品类</option>
            <option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.name }}
            </option>
          </select>
        </div>
        <div class="form-group">
          <label>优惠折扣：</label>
          <input type="number" min="0" max="100" v-model="editingStrategy.discount_rate" />
        </div>
        <div class="form-group">
          <label>开始时间：</label>
          <input type="datetime-local" v-model="editingStrategy.start_time" />
        </div>
        <div class="form-group">
          <label>结束时间：</label>
          <input type="datetime-local" v-model="editingStrategy.end_time" />
        </div>
        <div class="form-group">
          <label>持续时间：</label>
          <input type="number" min="1" v-model="editingStrategy.duration" />
        </div>
        <div class="form-group">
          <label>状态：</label>
          <select v-model="editingStrategy.status">
            <option value="active">上架</option>
            <option value="inactive">下架</option>
          </select>
        </div>
        <div class="dialog-buttons">
          <button @click="updateStrategy">保存</button>
          <button @click="showEditDialog = false" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'MarketingStrategyManagement',
  data() {
    return {
      strategies: [],
      categories: [],
      newStrategy: {
        name: '',
        description: '',
        category_id: '',
        discount_rate: '',
        start_time: '',
        end_time: '',
        duration: '',
        status: 'active'
      },
      showEditDialog: false,
      editingStrategy: null
    }
  },
  computed: {
    isValidStrategy() {
      return this.newStrategy.name && 
             this.newStrategy.category_id && 
             this.newStrategy.discount_rate && 
             this.newStrategy.start_time && 
             this.newStrategy.end_time &&
             this.newStrategy.duration
    }
  },
  created() {
    this.fetchStrategies()
    this.fetchCategories()
  },
  methods: {
    formatDateTime(datetime) {
      if (!datetime) return '未设置'
      return new Date(datetime).toLocaleString()
    },
    getCategoryName(categoryId) {
      const category = this.categories.find(c => c.id === categoryId)
      return category ? category.name : '未设置'
    },
    async fetchCategories() {
      try {
        const response = await axios.get('/api/categories', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.categories = response.data
      } catch (error) {
        console.error('获取商品品类列表失败:', error)
        alert('获取商品品类列表失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async fetchStrategies() {
      try {
        const response = await axios.get('/api/marketing-strategies', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.strategies = response.data
      } catch (error) {
        console.error('获取策略列表失败:', error)
        alert('获取策略列表失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async addStrategy() {
      if (!this.isValidStrategy) {
        alert('请填写完整的策略信息')
        return
      }
      try {
        const strategyData = {
          ...this.newStrategy,
          discount_rate: parseFloat(this.newStrategy.discount_rate),
          duration: parseInt(this.newStrategy.duration)
        }
        console.log('添加策略数据:', strategyData)
        
        const response = await axios.post('/api/marketing-strategies', strategyData, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.fetchStrategies()
        this.newStrategy = { 
          name: '', 
          description: '', 
          category_id: '',
          discount_rate: '',
          start_time: '', 
          end_time: '',
          duration: '',
          status: 'active'
        }
        alert('添加策略成功')
      } catch (error) {
        console.error('添加策略失败:', error)
        alert('添加策略失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    editStrategy(strategy) {
      this.editingStrategy = { ...strategy }
      this.showEditDialog = true
    },
    async updateStrategy() {
      try {
        const strategyData = {
          ...this.editingStrategy,
          discount_rate: parseFloat(this.editingStrategy.discount_rate),
          duration: parseInt(this.editingStrategy.duration)
        }
        console.log('更新策略数据:', strategyData)
        
        await axios.put(`/api/marketing-strategies/${this.editingStrategy.id}`, strategyData, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        this.fetchStrategies()
        this.showEditDialog = false
        alert('更新策略成功')
      } catch (error) {
        console.error('更新策略失败:', error)
        alert('更新策略失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    async toggleStrategyStatus(strategy) {
      try {
        const newStatus = strategy.status === 'active' ? 'inactive' : 'active'
        console.log('更新策略状态:', { status: newStatus })
        
        await axios.put(`/api/marketing-strategies/${strategy.id}/status`, { 
          status: newStatus 
        }, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        this.fetchStrategies()
        alert(`策略${newStatus === 'active' ? '上架' : '下架'}成功`)
      } catch (error) {
        console.error('更新策略状态失败:', error)
        alert('更新策略状态失败：' + (error.response?.data?.message || '未知错误'))
      }
    }
  }
}
</script>

<style scoped>
.marketing-strategy-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.back-btn {
  padding: 8px 16px;
  background-color: #909399;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.add-strategy-form {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.add-strategy-form textarea {
  width: 100%;
  min-height: 100px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.strategy-table {
  width: 100%;
  border-collapse: collapse;
}

.strategy-table th,
.strategy-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.strategy-table th {
  background-color: #f5f5f5;
}

button {
  margin: 0 5px;
  padding: 5px 10px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #66b1ff;
}

button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-badge.active {
  background-color: #67c23a;
  color: white;
}

.status-badge.inactive {
  background-color: #f56c6c;
  color: white;
}

.status-btn {
  font-size: 12px;
}

.status-btn.activate {
  background-color: #67c23a;
}

.status-btn.deactivate {
  background-color: #f56c6c;
}

.edit-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.edit-dialog-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 500px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group textarea {
  min-height: 100px;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn {
  background-color: #909399;
}

.cancel-btn:hover {
  background-color: #a6a9ad;
}
</style> 